<?php

namespace services\base;

use api\modules\v1\forms\base\JobForm;
use common\components\Service;
use common\helpers\RedisHelper;
use common\models\base\Job;
use services\log\LogMemberOpService;
use services\member\AttrService;
use Yii;

/**
 * Class JobService
 * @package services\base
 */
class JobService extends Service
{
    /**
     * 用户列表
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getListPage(array $params = [], int $page = 0, int $pageSize = 0): array
    {
        $query = Job::find()
            ->select(['*']);
        if (isset($params['status']) && is_numeric($params['status'])) {
            $query->andWhere(['status' => $params['status']]);
        } else {
            $query->andWhere(['status' => [Job::STATUS_INVALID, Job::STATUS_ENABLE]]);
        }
        $order = ['status' => SORT_DESC, 'sort' => SORT_ASC, 'id' => SORT_ASC];

        return $this->getListPageRes($query, $page, $pageSize, $order);
    }

    /**
     * 格式化列表
     * @param array $data
     * @return array
     */
    public function getListPageFormat(array $data = []): array
    {
        $list = [];
        foreach ($data as $row) {
            $list[] = [
                'id' => $row['id'],
                'job_name' => $row['job_name'],
                'sort' => $row['sort'],
//                'status' => $row['status'],
                'status_str' => Job::$statuss[$row['status']] ?? '',
//                'created_at_str' => DateHelper::timestampToDate($row['created_at']),
            ];
        }
        return $list;
    }

    /**
     * 岗位详情
     * @param array $params
     * @return array
     */
    public function getInfo(int $id): array
    {
        $data = [];
        // 岗位信息
        $job = Job::findOne($id);
        if ($job) {
            $data = [
                'id' => $job->id,
                'job_name' => $job->job_name,
                'status' => $job->status,
                'sort' => $job->sort,
            ];
        }

        return $data;
    }

    /**
     * 详情绑定岗位列表
     * @param int|array|null $orId
     * @return array
     */
    public static function getEditCondition($orId = null): array
    {
        $query = Job::find()
            ->select(['id value', 'job_name label'])
            ->where(['status' => Job::STATUS_ENABLE]);
        if ($orId) {
            $query->orWhere([
                'id' => $orId,
                'status' => [Job::STATUS_INVALID, Job::STATUS_ENABLE]
            ]);
        }
        return $query->asArray()->all();
    }

    /**
     * 编辑岗位
     * @param Job $job
     * @param JobForm $model
     * @return Job
     * @throws \Exception
     */
    public static function editModel(Job $job, JobForm $model): Job
    {
        $job->job_name = $model->job_name;
        $job->status = $model->status;
        $job->sort = $model->sort;
        $job->operation_id = Yii::$app->user->identity->member_id;
        $job->operation_name = Yii::$app->user->identity->member->realname;
        $job->saveAndCheckResult();

        return $job;
    }

    /**
     * 新增岗位
     * @param JobForm $model
     * @return array
     */
    public function create(JobForm $model): array
    {
        try {
            $transaction = Yii::$app->db->beginTransaction();

            // 1.新增岗位
            $job = new Job();
            $job = self::editModel($job, $model);

            // 2.日志
            LogMemberOpService::createJobLog($model, $job);

            $transaction->commit();
            return ['id' => $job->id];
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }

    /**
     * 编辑岗位
     * @param JobForm $model
     * @return array
     */
    public function edit(JobForm $model): array
    {
        try {
            $transaction = Yii::$app->db->beginTransaction();

            // 1.更新岗位
            $oldJob = new Job();
            $oldJob->setAttributes($model->getJob()->getAttributes());
            $job = self::editModel($model->getJob(), $model);

            // 2.日志
            LogMemberOpService::createJobLog($model, $job, $oldJob);

            // 3.更新缓存
            RedisHelper::setJob($job);

            $transaction->commit();
            return ['id' => $job->id];
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }

    /**
     * 删除岗位
     * @param JobForm $model
     * @return array
     */
    public function delete(JobForm $model): array
    {
        try {
            $transaction = Yii::$app->db->beginTransaction();

            // 1.更新岗位
            $job = $model->getJob();
            $job->status = Job::STATUS_DELETE;
            $job->operation_id = Yii::$app->user->identity->member_id;
            $job->operation_name = Yii::$app->user->identity->member->realname;
            $job->saveAndCheckResult();
            // 2.日志
            LogMemberOpService::createJobLog($model, $job);
            // 3.解绑岗位
            AttrService::unBindJob($job->id);
            // 4.更新缓存
            RedisHelper::delJob($job->id);

            $transaction->commit();
            return ['id' => $job->id];
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }
}
